package com.shop.shop_end.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.shop.shop_end.entity.User;
import com.shop.shop_end.mapper.UserMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Component
public class TokenUtils {
    private static UserMapper staticUserMapper;

    @Resource
    private UserMapper userMapper;

    @PostConstruct
    public void setUserService(){
        staticUserMapper = userMapper;
    }

    private TokenUtils(){

    }

    /**
     * 生成token
     */
    public static String generateToken(Long userId, String role, String sign){
        return JWT.create().withAudience(String.valueOf(userId), role) //将userId和role 保存到token里，作为荷载
                .withExpiresAt(DateUtil.offsetHour(new Date(), 7)) //7小时后token过期
                .sign(Algorithm.HMAC256(sign));//以password作为token的秘钥
    }

    /**
     * 获取当前登录的用户信息【id，role，password】
     */
    public static List<String> getCurrentUserInfo(String token){
        try {
            if (StrUtil.isNotBlank(token)) {
                List<String> audience = JWT.decode(token).getAudience();
                System.out.println("audience==>"+ audience);
                return audience;
            }
        }catch (Exception e){
            return null;
        }
        return null;
    }
}
